package com.xdf.teacher.utils;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.alibaba.fastjson.JSON;
import com.bkrtc_sdk.bkrtc_impl;
import com.xdf.teacher.constant.RpcConstant;
import com.xdf.teacher.entity.UserBean;

import net.neiquan.applibrary.utils.SpUtil;
import net.neiquan.okhttp.NetCallBack;
import net.neiquan.okhttp.ResultModel;

import org.haitao.common.utils.AppLog;
import org.haitao.common.utils.PixelUtil;
import org.json.JSONException;
import org.json.JSONObject;
import org.webrtc.BuKaCamera;
import org.webrtc.BuKaCameraDevice;
import org.webrtc.SurfaceViewRenderer;

import java.util.Collections;
import java.util.List;

import tv.buka.sdk.BukaSDK;
import tv.buka.sdk.BukaSDKManager;
import tv.buka.sdk.BukaSDKVersion;
import tv.buka.sdk.entity.Chat;
import tv.buka.sdk.entity.Num;
import tv.buka.sdk.entity.Room;
import tv.buka.sdk.entity.Rpc;
import tv.buka.sdk.entity.Status;
import tv.buka.sdk.entity.Stream;
import tv.buka.sdk.entity.User;
import tv.buka.sdk.listener.ChatListener;
import tv.buka.sdk.listener.ConnectListener;
import tv.buka.sdk.listener.NetWorkListener;
import tv.buka.sdk.listener.ReceiptListener;
import tv.buka.sdk.listener.RpcListener;
import tv.buka.sdk.listener.StatusListener;
import tv.buka.sdk.listener.UserListener;
import tv.buka.sdk.utils.HttpUtils;
import tv.buka.sdk.utils.ResponseUtils;
import tv.buka.sdk.v3.config.Url;

import static android.R.attr.id;

/**
 * Created by Administrator on 2017/12/7 0007.
 */

public class BukaHelper {

    private static BukaHelper sInstance;
    private Activity mContext;
    private int mCameraId = 1;
    private SurfaceViewRenderer mPublishStreamStatus;
    private long aid = 0;
    private long vid = 0;
    private UserBean userBean;
    private LinearLayout mStreamLayout;

    public UserBean getUserBean() {
        return userBean;
    }

    public void setUserBean(UserBean userBean) {
        this.userBean = userBean;
    }

    public Stream getStatus() {
        return status;
    }

    public void setStatus(Stream status) {
        this.status = status;
    }

    private Stream status;

    private BukaHelper(Activity context) {
        this.mContext = context;
    }

    public static synchronized BukaHelper getInstance(Activity context) {
        if (sInstance == null) {
            sInstance = new BukaHelper(context);
        }
        return sInstance;
    }

    //初始化buksSdk及需要的views
    public void initBukaViews(final UserBean userBean, final LinearLayout mStreamLayout) {
        this.userBean = userBean;
        this.mStreamLayout = mStreamLayout;
        this.initBuka();
        BukaSDKManager.getConnectManager().connect(userBean.getUser_id(), "",
                new ReceiptListener() {

                    @Override
                    public void onSuccess(Object o) {
                        // TODO Auto-generated method stub
                        login();
                    }

                    @Override
                    public void onError() {
                        // TODO Auto-generated method stub
                        if (onLoginListener != null) {
                            onLoginListener.onStatusListener(0, "连接聊天室失败,请重新进入");
                        }
                    }
                });
    }

    private void initBuka() {
//        BukaSDK.setSingalServerGroupUrl("http://vc.xdf.cn/xdf/signaling/");
//        BukaSDK.setMediaServerGroupUrl("http://vc.xdf.cn");
//        BukaSDK.setMediaServerNamespace("xdf");
//        BukaSDK.init("c7c6b2a6a623f3ec022aa61f5aa4fa63",
//                mContext, BukaSDKVersion.BukaSDKVersion3);
        BukaSDKManager.getConnectManager().addListener(connectListener);
        BukaSDKManager.getUserManager().addListener(userListener);
        BukaSDKManager.getChatManager().addListener(chatListener);
        BukaSDKManager.getRpcManager().addListener(rpcListener);
        BukaSDKManager.getStatusManager().addListener(statusListener);
//        BukaSDK.start();
    }

    //登录bukaSdk
    private void login() {
        BukaSDKManager.getUserManager().login(
                userBean.getCourse_id(),
                JSON.toJSONString(userBean),
                new ReceiptListener() {

                    @Override
                    public void onSuccess(Object o) {
                        if (onLoginListener != null) {
                            onLoginListener.onStatusListener(2, "登录聊天室成功...");
                        }
                        AppLog.e("当前房间人数"
                                + BukaSDKManager
                                .getUserManager()
                                .getUserArr()
                                .size());
                        final List<Status> statusList = BukaSDKManager.getStatusManager().getStatusArr("stream");
                        if (statusList != null && statusList.size() > 0) {
                            for (int i = 0; i < statusList.size(); i++) {
                                final Status status = statusList.get(i);
                                if (getSessionUser(status.getSession_id()).getRole() == 1) {
                                    play_(status, mStreamLayout);
                                } else {
                                    if (!TextUtils.equals(status.getSession_id(), getCurrentUser().getSession_id())) {
                                        play(status);
                                    }
                                }
                            }
                        }
                    }

                    @Override
                    public void onError() {
                        if (onLoginListener != null) {
                            onLoginListener.onStatusListener(1, "登录聊天室失败,请重新进入");
                        }
                    }
                });
    }

    //获取当前用户的信息（用户属性实时更新的）
    public UserBean getCurrentUser() {
        BukaSDKManager.getUserManager().getSelfUser(new ReceiptListener<User>() {
            @Override
            public void onSuccess(User user) {
//                userBean = new UserBean(user.getUser_extend());
                userBean.setSession_id(user.getSession_id());
            }

            @Override
            public void onError() {
//                userBean = null;
                userBean.setSession_id("");
            }
        });
        return userBean;
    }

    private UserBean userBean1;

    public UserBean getSessionUser(String seesion_id) {
        BukaSDKManager.getUserManager().getUser(seesion_id, new ReceiptListener<User>() {
            @Override
            public void onSuccess(User user) {
                userBean1 = new UserBean(user.getUser_extend());
                userBean1.setSession_id(user.getSession_id());
            }

            @Override
            public void onError() {
                userBean1 = null;
            }
        });
        return userBean1;
    }

    private boolean updateSelfUser = false;

    public void updateUser(UserBean userBean) {
        updateSelfUser = true;
        BukaSDKManager.getUserManager().update(JSON.toJSONString(userBean), new ReceiptListener<Object>() {
            @Override
            public void onSuccess(Object o) {
            }

            @Override
            public void onError() {
            }
        });
    }

    //推流
    public void publish(final LinearLayout mStreamLayout) {
        BukaSDKManager.getMediaManager().startPulish(2, mCameraId, mCameraId, true, true, "stream_info", 320, 180, 500, 15, new ReceiptListener<Stream>() {
            @Override
            public void onSuccess(Stream status) {
                AppLog.e("推流成功");
                //=======dyj
                mStreamLayout.removeAllViews();
                ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                status.getSvr().setLayoutParams(layoutParams);
                //=======dyj
                mStreamLayout.setVisibility(View.VISIBLE);
                mStreamLayout.addView(status.getSvr());
                mPublishStreamStatus = status.getSvr();
                aid = status.getAid();
                vid = status.getVid();
                BukaHelper.this.status = status;
                BukaSDKManager.getMediaManager().setInputMute(status, true);
            }

            @Override
            public void onError() {
                AppLog.e("推流失败");
            }
        });
    }

    public void stopPublish(final LinearLayout mStreamLayout) {
        BukaSDKManager.getMediaManager().stopPublish(new ReceiptListener<SurfaceViewRenderer>() {
            @Override
            public void onSuccess(SurfaceViewRenderer renderer) {
                AppLog.e("停止推流");
                mStreamLayout.removeAllViews();
//                mStreamLayout.setVisibility(View.GONE);
                status = null;
            }

            @Override
            public void onError() {
                AppLog.e("停止推流失败");
            }
        });
    }


    public void play(Status status) {
        try {
            JSONObject extend = new JSONObject(status.getStatus_extend());
            JSONObject stream = new JSONObject(extend.getString("stream_info"));
            long aid = stream.getLong("aid");
            long vid = stream.getLong("vid");
            AppLog.e(aid + "=========play=========" + vid);
            BukaSDKManager.getMediaManager().startPlay(aid, vid, false, true, new ReceiptListener<SurfaceViewRenderer>() {
                @Override
                public void onSuccess(SurfaceViewRenderer renderer) {
                    AppLog.e("play拉流");
                }

                @Override
                public void onError() {
                    AppLog.e("play拉流失败");
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void play_(Status status, final LinearLayout mStreamLayout) {
        try {
            JSONObject extend = new JSONObject(status.getStatus_extend());
            JSONObject stream = new JSONObject(extend.getString("stream_info"));
            long aid = stream.getLong("aid");
            long vid = stream.getLong("vid");
            AppLog.e(aid + "=========play_=========" + vid);
            BukaSDKManager.getMediaManager().startPlay(aid, vid, new ReceiptListener<SurfaceViewRenderer>() {
                @Override
                public void onSuccess(SurfaceViewRenderer renderer) {
                    ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                    renderer.setLayoutParams(layoutParams);
                    AppLog.e("play_拉流");
                    mStreamLayout.removeAllViews();
                    mStreamLayout.addView(renderer);
                    mStreamLayout.setVisibility(View.VISIBLE);
                }

                @Override
                public void onError() {
                    AppLog.e("play_拉流失败");
//                    mStreamLayout.removeAllViews();
//                    mStreamLayout.setVisibility(View.GONE);
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void playWithVideo(Status status, final LinearLayout mStreamLayout) {
        try {
            JSONObject extend = new JSONObject(status.getStatus_extend());
            JSONObject stream = new JSONObject(extend.getString("stream_info"));
            long aid = stream.getLong("aid");
            long vid = stream.getLong("vid");
            AppLog.e(aid + "=========playWithVideo=========" + vid);
            BukaSDKManager.getMediaManager().startPlay(aid, vid, true, false, new ReceiptListener<SurfaceViewRenderer>() {
                @Override
                public void onSuccess(SurfaceViewRenderer renderer) {
                    ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                    renderer.setLayoutParams(layoutParams);
                    AppLog.e("playWithVideo拉流");
                    mStreamLayout.removeAllViews();
                    mStreamLayout.addView(renderer);
                    mStreamLayout.setVisibility(View.VISIBLE);
                }

                @Override
                public void onError() {
                    AppLog.e("playWithVideo拉流失败");
//                    mStreamLayout.removeAllViews();
//                    mStreamLayout.setVisibility(View.GONE);
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void playWithOutVidoAndAudio(Status status) {
        try {
            JSONObject extend = new JSONObject(status.getStatus_extend());
            JSONObject stream = new JSONObject(extend.getString("stream_info"));
            long aid = stream.getLong("aid");
            long vid = stream.getLong("vid");
            AppLog.e(aid + "=========playWithOutVidoAndAudio=========" + vid);
            BukaSDKManager.getMediaManager().startPlay(aid, vid, false, false, new ReceiptListener<SurfaceViewRenderer>() {
                @Override
                public void onSuccess(SurfaceViewRenderer renderer) {
                    AppLog.e("playWithOutVidoAndAudio拉流");
                }

                @Override
                public void onError() {
                    AppLog.e("playWithOutVidoAndAudio拉流失败");
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    public void play2_(boolean silence) {
        stopPlay(mStreamLayout);
        final List<Status> statusList = BukaSDKManager.getStatusManager().getStatusArr("stream");
        if (statusList != null && statusList.size() > 0) {
            for (int i = 0; i < statusList.size(); i++) {
                final Status status = statusList.get(i);
                AppLog.e("=========play2_=========");
                if (getSessionUser(status.getSession_id()).getRole() == 1) {
                    if (silence) {
                        playWithVideo(status, mStreamLayout);
                    } else {
                        play_(status, mStreamLayout);
                    }
                } else {
                    if (!TextUtils.equals(status.getSession_id(), getCurrentUser().getSession_id())) {
                        if (silence) {
                            playWithOutVidoAndAudio(status);
                        } else {
                            play(status);
                        }
                    }
                }
            }
        }
    }

    public void stopPlay(final LinearLayout mStreamLayout) {
        final List<Status> statusList = BukaSDKManager.getStatusManager().getStatusArr("stream");
        AppLog.e("=========stopPlay000=========" + (statusList != null ? statusList.size() : 0));
        if (statusList != null && statusList.size() > 0) {
            for (int i = 0; i < statusList.size(); i++) {
                Status status = statusList.get(i);
                try {
                    JSONObject extend = new JSONObject(status.getStatus_extend());
                    JSONObject stream = new JSONObject(extend.getString("stream_info"));
                    long aid = stream.getLong("aid");
                    long vid = stream.getLong("vid");
                    AppLog.e("=========stopPlay111=========" + statusList.size());
                    AppLog.e(aid + "=========stopPlay222=========" + vid);
                    BukaSDKManager.getMediaManager().stopPlay(aid, vid, new ReceiptListener<SurfaceViewRenderer>() {
                        @Override
                        public void onSuccess(SurfaceViewRenderer renderer) {
                            AppLog.e("停止拉流");
                            mStreamLayout.removeAllViews();
                            mStreamLayout.setVisibility(View.GONE);
                        }

                        @Override
                        public void onError() {
                            AppLog.e("停止拉流失败");
                            mStreamLayout.removeAllViews();
                            mStreamLayout.setVisibility(View.GONE);
                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        } else {
            mStreamLayout.removeAllViews();
            mStreamLayout.setVisibility(View.GONE);
        }
    }

    public void stopPlay_(Status status, final LinearLayout mStreamLayout_) {
        try {
            JSONObject extend = new JSONObject(status.getStatus_extend());
            JSONObject stream = new JSONObject(extend.getString("stream_info"));
            long aid = stream.getLong("aid");
            long vid = stream.getLong("vid");
            AppLog.e(aid + "=========stopPlay_=========" + vid);
            BukaSDKManager.getMediaManager().stopPlay(aid, vid, new ReceiptListener<SurfaceViewRenderer>() {
                @Override
                public void onSuccess(SurfaceViewRenderer renderer) {
                    AppLog.e("stopPlay_停止拉流");
                    mStreamLayout_.removeAllViews();
                    mStreamLayout_.setVisibility(View.GONE);
                }

                @Override
                public void onError() {
                    AppLog.e("stopPlay_停止拉流失败");
                    mStreamLayout_.removeAllViews();
                    mStreamLayout_.setVisibility(View.GONE);
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void stopPlay2_(Status status) {
        try {
            JSONObject extend = new JSONObject(status.getStatus_extend());
            JSONObject stream = new JSONObject(extend.getString("stream_info"));
            long aid = stream.getLong("aid");
            long vid = stream.getLong("vid");
            AppLog.e(aid + "=========stopPlay2_=========" + vid);
            BukaSDKManager.getMediaManager().stopPlay(aid, vid, new ReceiptListener<SurfaceViewRenderer>() {
                @Override
                public void onSuccess(SurfaceViewRenderer renderer) {
                    AppLog.e("stopPlay2_停止拉流");
                }

                @Override
                public void onError() {
                    AppLog.e("stopPlay2_停止拉流失败");
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //退出登录
    public void logout() {
        BukaSDKManager.getUserManager().logout(new ReceiptListener() {
            @Override
            public void onSuccess(Object o) {
                AppLog.e("退出登录");
                BukaSDKManager.getRpcManager().removeListener(rpcListener);
                BukaSDKManager.getStatusManager().removeListener(statusListener);
                BukaSDKManager.getUserManager().removeListener(userListener);
                BukaSDKManager.getChatManager().removeListener(chatListener);
                BukaSDKManager.getConnectManager().removeListener(connectListener);
                BukaSDKManager.getConnectManager().disconnect();
            }

            @Override
            public void onError() {
                // TODO Auto-generated method stub
                AppLog.e("退出登录失败");
            }
        });
    }

    //摄像头转换
    public void switchCamera() {
        if (mPublishStreamStatus != null) {
            mCameraId = mCameraId == 0 ? 1 : 0;
//        public void switchCamera(int cameraId, long aid, long vid, int cameraRotation, int width, int height, int maxFramerate, SurfaceViewRenderer surface) {
            BukaSDKManager.getMediaManager().switchCamera(mCameraId, aid, vid, mCameraId, PixelUtil.getScreenWidth(mContext) * 141 / 400, PixelUtil.getScreenWidth(mContext) * 141 / 400 * 16 / 9, 10, mPublishStreamStatus);
        }
    }

    //聊天sessionId传null则为群聊，否则单聊
    public void chat(final String sessionId, String content) {
        ReceiptListener listener = new ReceiptListener() {
            @Override
            public void onSuccess(Object o) {
                // TODO Auto-generated
                // method
                // stub
            }

            @Override
            public void onError() {
                // TODO Auto-generated
                // method
                // stub
            }
        };
        if (sessionId == null) {
            BukaSDKManager.getChatManager()
                    .sendBroadcastChat(
                            content,
                            listener);
        } else {
            BukaSDKManager.getChatManager()
                    .sendUnicastChat(
                            content,
                            sessionId, listener);
        }
    }

    //聊天sessionId传null则为群聊，否则单聊
    public void rpc(final String sessionId, long type, String content) {
        ReceiptListener listener = new ReceiptListener() {

            @Override
            public void onSuccess(Object o) {
                // TODO Auto-generated
                // method
                // stub
            }

            @Override
            public void onError() {
                // TODO Auto-generated
                // method
                // stub
//                ToastUtil.shortShowToast("操作失败");
            }
        };
        if (sessionId == null) {
            BukaSDKManager
                    .getRpcManager()
                    .sendBroadcastRpc(
                            content,
                            type,
                            0,
                            listener);
        } else {
            BukaSDKManager.getRpcManager()
                    .sendUnicastRpc(
                            content,
                            type, 0, sessionId, listener);
        }
    }

    public void exit(final LinearLayout mStreamLayout, final LinearLayout mStreamLayout_) {
        stopPlay(mStreamLayout);
        stopPublish(mStreamLayout_);
        BukaSDKManager.getRpcManager().sendBroadcastRpc("", 1020, 0);
        logout();
    }

    ConnectListener connectListener = new ConnectListener() {

        @Override
        public void onSessionPackageLost() {
            // TODO Auto-generated method stub
            AppLog.e("===========111==============");
        }

        @Override
        public void onSessionOff() {
            // TODO Auto-generated method stub
            AppLog.e("===========222==============");
            if (onLoginListener != null && userBean != null) {
                onLoginListener.onStatusListener(3, "当前帐号" + userBean.getUser_nickname() + "异地登录，被迫下线！");
            }
        }

        @Override
        public void onSessionDisconnected() {
            // TODO Auto-generated method stub
            AppLog.e("===========333==============");
            if (onLoginListener != null) {
                onLoginListener.onStatusListener(4, "您已断开连接,请重新进入");
            }
        }

        @Override
        public void onSessionConnected() {
            // TODO Auto-generated method stub
            AppLog.e("===========444==============");
            final List<Status> statusList = BukaSDKManager.getStatusManager().getStatusArr("stream");
            if (statusList != null && statusList.size() > 0) {
                for (int i = 0; i < statusList.size(); i++) {
                    final Status status = statusList.get(i);
                    if (getSessionUser(status.getSession_id()).getRole() == 1) {
                        play_(status, mStreamLayout);
                    } else {
                        if (!TextUtils.equals(status.getSession_id(), getCurrentUser().getSession_id())) {
                            play(status);
                        }
                    }
                }
            }
        }

        @Override
        public void onServerArrChanged() {
            // TODO Auto-generated method stub
            AppLog.e("===========555==============");
            if (!BukaSDKManager.getConnectManager().isConnect()
                    && !BukaSDKManager.getConnectManager().isConnecting()) {
                AppLog.e("===========666==============");
            }
        }
    };

    UserListener userListener = new UserListener() {

        @Override
        public void onUserIn(User user) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onUserChanged(User oldUser, User user) {
            // TODO Auto-generated method stub
            if (updateSelfUser) {
                updateSelfUser = false;
                return;
            }
            if (onUserListener != null) {
                onUserListener.onUserListener(oldUser, user);
            }
        }

        @Override
        public void onUserNumChanged(Num num) {
            // TODO Auto-generated method stub
            //房间人数
            AppLog.e("房间人数变成" + num.getValue());
        }

        @Override
        public void onUserOut(User user) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onUserDisconnect(User user) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onSelfDisconnect() {
            // TODO Auto-generated method stub
            AppLog.e("您已断线");
        }

        @Override
        public void onSelfConnect(Room room) {
            AppLog.e("您已重连成功");
        }

    };

    ChatListener chatListener = new ChatListener() {

        @Override
        public void onChatReceive(final Chat chat) {
            // TODO Auto-generated method stub
            BukaSDKManager.getUserManager().getUser(
                    chat.getSend_session_id(), new ReceiptListener<User>() {
                        @Override
                        public void onSuccess(User user) {
                            if (user != null) {

                            } else {
                                AppLog.e("收到消息，但未找到此人信息");
                            }

                        }

                        @Override
                        public void onError() {

                        }
                    });
        }
    };

    RpcListener rpcListener = new RpcListener() {

        @Override
        public void onRpcReceive(final Rpc rpc) {
            // TODO Auto-generated method stub
            if (onRpcListener != null) {
                onRpcListener.onRpcListener(rpc);
            }
        }
    };

    StatusListener statusListener = new StatusListener() {

        @Override
        public void onStatusDelete(Status status) {
            // TODO Auto-generated method stub
            AppLog.e(status.getSession_id() + "==========状态删除========" + status.getStatus_extend());
            if (onStatusListener != null) {
                onStatusListener.onStatusListener(1, status);
            }
        }

        @Override
        public void onStatusAdd(Status status) {
            // TODO Auto-generated method stub
            AppLog.e(status.getSession_id() + "==========状态添加111========" + status.getStatus_extend());
            AppLog.e("==========状态添加222========" + status.getTag());
            if (onStatusListener != null) {
                onStatusListener.onStatusListener(2, status);
            }
        }

        @Override
        public void onStatusChanged(Status status, Status status1) {

        }
    };

    private OnStatusListener onStatusListener;

    public void setOnStatusListener(OnStatusListener onStatusListener) {
        this.onStatusListener = onStatusListener;
    }

    public interface OnStatusListener {
        void onStatusListener(int type, Status status);
    }

    private OnLoginListener onLoginListener;

    public void setOnLoginListener(OnLoginListener onLoginListener) {
        this.onLoginListener = onLoginListener;
    }

    public interface OnLoginListener {
        void onStatusListener(int type, String str);
    }

    private OnRpcListener onRpcListener;

    public void setOnRpcListener(OnRpcListener onRpcListener) {
        this.onRpcListener = onRpcListener;
    }

    public interface OnRpcListener {
        void onRpcListener(Rpc rpc);
    }

    private OnUserListener onUserListener;

    public void setOnUserListener(OnUserListener onUserListener) {
        this.onUserListener = onUserListener;
    }

    public interface OnUserListener {
        void onUserListener(User oldUser, User user);
    }
}
